'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 离开战斗
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var Code = require('../../../consts/code');
var copyRecordModel = require('../../../models/copyRecordModel');
var fightRewardUtil = require('../../../util/fightRewardUtil');
var roleService = require('../../../services/roleService');
var rewardService = require('../../../services/rewardService');
var copyService = require('../../../services/copyService');
var PlayerManager = require('../../../libs/playerManager');
var moduleType = require('../../../consts/moduleType.js');
var operationType = require('../../../consts/operationType.js');

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

/**
 * 离开副本
 * 需要上传的数据:
 * 1.已经拆除的建筑
 * 2.已经打过的经济类的建筑
 * 3.要统计的数据
 */
Handler.prototype.exit = function (msg, session, next) {
    var role_id = session.uid;
    var record_id = msg.record_id;
    var damage_build_list = msg.damage_build_list || [];
    if (!record_id) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var copy_record_model;
    var player_manager = new PlayerManager(role_id);

    var add_train_exp_soldier_list;
    async.waterfall(
        [
            function (cb) {
                copyRecordModel.getRecordByAtkRoleId(role_id, record_id, cb);
            },
            function (model, cb) {
                copy_record_model = model;
                if (!copy_record_model) {
                    return next(null, {
                        code: Code.COPY_RECORD_NOT_EXIST
                    });
                }

                if (copy_record_model.getStar() !== undefined) {
                    return next(null, {
                        code: Code.COPY_HAVE_PASS
                    });
                }
                cb();
            },
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['role', 'copy', 'bag', 'skill', 'soldier', 'build', 'task', 'daily_task', 'achieve', 'tech', 'sevenDayActivity', 'accrued'],
                    cb);
            },
            function (cb) {
                // 打到的资源
                var add_gold = _getEconomyBuildGold(copy_record_model, damage_build_list);

                // 毁坏建筑能拿到的经验
                var add_exp = _getDestroyBuildExp(copy_record_model, damage_build_list);

                // 副本的星级
                var star = _getStar(copy_record_model, damage_build_list);

                // 是否有双倍卡次数true+英雄经验
                // var copy_model = player_manager.copy;
                // if (copy_model.getDoubleCopyExpNum() >= 1) {
                //     copy_model.subDoubleCopyExpNum();
                //     roleService.addExp(player_manager, add_exp * 2);
                // } else {
                //     roleService.addExp(player_manager, add_exp);
                // }
                roleService.addExp(player_manager, add_exp);

                // 添加金币
                add_gold = roleService.addGoldLimit(player_manager, add_gold);

                // 给用户添加副本宝箱奖励
                if (!!copy_record_model.canLucky()) {
                    var random_reward = copy_record_model.getReward();
                    rewardService.addRewardToRole(player_manager, random_reward, moduleType.MDL_COPY, operationType.OPR_COPY_LUCKY_BOX);
                }

                // 设置副本的奖励数据
                copy_record_model.setStar(star);
                copy_record_model.setEarnGold(add_gold);
                copy_record_model.setEarnExp(add_exp);

                if (star > 0) {
                    copyService.passCopy(player_manager, copy_record_model.copy_id, star);
                }
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            copy_record_model.save();
            return next(null, {
                code: Code.OK,
                result: {
                    def_name: copy_record_model.getDefName(),
                    add_gold: copy_record_model.getEarnGold(),
                    add_exp: copy_record_model.getEarnExp(),
                    add_cup: 0,
                    star: copy_record_model.getStar(),
                    progress: copy_record_model.getProgress(),
                    reward_list: copy_record_model.getRewardList()
                }
            });
        }
    );
};

/**
 * 获取毁坏的经济类建筑能拿到的资源
 */
var _getEconomyBuildGold = function (copy_record_model, damage_build_list) {
    return fightRewardUtil.getEconomyBuildGold(copy_record_model, damage_build_list);
};

/**
 * 获取星级
 * @param  {[type]} copy_record_model  [description]
 * @param  {[type]} damage_build_list [description]
 * @return {[type]}                    [description]
 */
var _getStar = function (copy_record_model, damage_build_list) {
    return fightRewardUtil.getStar(copy_record_model, damage_build_list);
};

/**
 * 获取已经销毁的建筑能获得的经验
 */
var _getDestroyBuildExp = function (copy_record_model, damage_build_list) {
    return fightRewardUtil.getDestroyBuildExp(copy_record_model, damage_build_list);
};
